package cn.mihoyo.tenement.controller;

import cn.mihoyo.base.util.AjaxResult;
import cn.mihoyo.base.util.PageList;
import cn.mihoyo.tenement.domain.Housing;
import cn.mihoyo.tenement.query.HousingQuery;
import cn.mihoyo.tenement.service.HousingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/housing")
public class HousingController {
    @Autowired
    private HousingService housingService;

    @GetMapping
    public List<Housing> findAll(){
        return housingService.findAll();
    }

    @GetMapping("/{id}")
    public Housing findById(@PathVariable("id") Long id){
        return housingService.findById(id);
    }

    @DeleteMapping("/{id}")
    public AjaxResult delete(@PathVariable("id") Long id){
        try {
            housingService.delete(id);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Housing Housing){
        try {
            if(Housing.getHId() == null || Housing.getHId() == 0){
                housingService.add(Housing);
            }else {
                housingService.update(Housing);
            }
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    @PostMapping
    public PageList queryByPage(@RequestBody HousingQuery query){
        return housingService.queryByPage(query);
    }
}
